/**
 * @authors tanqichao
 * @date    2017-06-07 13:59:27
 * @module  创意列表
 */

import { Form, Row, Col, Input, Button, Select, Table, Radio, DatePicker, Pagination, Switch, Icon } from 'antd';
import { AccessControl } from '../../utils/common';
import RangePicker from '../plugin/rangePicker';
import { pageSize } from '../../constants';
import React, { Component } from 'react';
import { createForm } from 'rc-form';
import MaterialModal from './item/materialData';

import Styles from './index.less';
import { Link } from 'dva/router';
import { connect } from 'dva';
import 'moment/locale/zh-cn';
import moment from 'moment';

moment.locale('zh-cn');

const RadioButton = Radio.Button;
const RadioGroup = Radio.Group;
const Option = Select.Option;
const FormItem = Form.Item;

class SearchList extends Component {
	constructor(props) {
		super(props);
		this.state = {
			page: 1,
			args: null,
			visible: false,
			beginTime: moment().format('YYYY-MM-DD'),
			endTime: moment().format('YYYY-MM-DD')
		}
	}

	// 初始化
	componentDidMount = () => {
		this.search()
  }

	// 分页
  handlePage = (page) => {
  	this.setState({
  		page: page
  	}, () => {
  		this.search()
  	})
  }

  // 切换时间
	handleRangePicker = (beginTime, endTime) => {
		this.setState({
			beginTime: moment(beginTime).format('YYYY-MM-DD'),
			endTime: moment(endTime).format('YYYY-MM-DD')
		}, () => {
			this.search()
		})
	}

	// 搜索
	search = () => {
		this.props.form.validateFields((err, values) => {
			const params = {
				beginTime: this.state.beginTime,
				endTime: this.state.endTime,
				title: values.title || '',
				page: this.state.page,
				pageSize: pageSize
			};
			this.setState({
				args: params
			});
			console.log('%c%s', 'color: #04B894', 'params:' + JSON.stringify(params));
			this.props.dispatch({
				type: 'packetList/fetch',
				payload: JSON.stringify(
					params
				)
			})
    })
	}

	// 查看素材统计数据
	fetchMaterialList = (crGrpIds) => {
		this.props.dispatch({
			type: 'packetList/fetchMaterial',
			payload: JSON.stringify({
				crGrpId: crGrpIds
			})
		})
		this.setState({
			visible: true
		})
	}

	// 关闭弹窗
	hide = () => {
		this.setState({
			visible: false
		})
	}

	render () {
		const { getFieldDecorator } = this.props.form;
    const permissionList = this.props.permissions;
		const columns = [{
		  title: '创意包ID',
		  dataIndex: 'id',
		  key: 'id'
		}, {
		  title: '创意包类型',
		  dataIndex: 'type',
		  key: 'type',
			render: (text, record) => {
				return text === 1 ? '互动广告' : '展示广告';
			}
		}, {
		  title: '创意包名称	',
		  dataIndex: 'title',
		  key: 'title',
			render: (text, record) => {
				return (
					<a onClick={this.fetchMaterialList.bind(this, record.id)}>{text}<span className={Styles.plusIcon}><Icon type="plus-circle-o" /></span></a>
				)
			}
		}, {
		  title: '曝光量',
		  dataIndex: 'exposureCount',
		  key: 'exposureCount'
		}, {
		  title: '点击量',
		  dataIndex: 'clickCount',
		  key: 'clickCount'
		}, {
		  title: '点击率',
		  dataIndex: 'clickRate',
		  key: 'clickRate'
		}, {
		  title: '点击均价（元）',
		  dataIndex: 'avgPrice',
		  key: 'avgPrice'
		}, {
		  title: '总消耗(元)',
		  dataIndex: 'consumeTotal',
		  key: 'consumeTotal'
		}, {
		  title: '操作',
		  dataIndex: 'status',
		  key: 'status',
		  render: (text, record) => {
		  	return AccessControl(permissionList, 'dsp_ad_modify') ? (
					<Link to={`/page/packet/edit/${record.type}/${record.id}`}>编辑</Link>
				): '';
		  }
		}
		];

		const pageConfig = {
    	className: "ant-table-pagination",
      total: this.props.totalCount,
      onChange: this.handlePage,
      current: this.state.page,
      pageSize: pageSize,
		};

		return (
			<div>
				<Form layout="inline">
					<div className={Styles.search}>
						<Row>
							<Col span={24}>
								<FormItem colon={false} className={Styles.mr45}>
									{getFieldDecorator('title')(
										<Input placeholder="请输入创意包名称" />
	                )}
								</FormItem>
								<Button type="primary" size="large" onClick={this.search} className={Styles.searchBtn}>搜索</Button>
							</Col>
						</Row>
					</div>
					<Row className={Styles.list}>
						<Col span={24} className={Styles.head}>
							<span className={Styles.subTitle}>所有创意包</span>
							{
								AccessControl(permissionList, 'dsp_ad_create') ?
									<span><Button size="large" type="primary" className={Styles.newInteractive}><Link to="/page/packet/createInteractive"><em>+</em>新建互动创意包</Link></Button>
									<Button size="large" type="primary" className={Styles.newTradition}><Link to="/page/packet/createTradition"><em>+</em>新建展示创意包</Link></Button></span>: null
							}
							<div className={Styles.timeFilter}>
								<RangePicker {...this.props} onComplete={this.handleRangePicker} />
							</div>
						</Col>
						<Col span={24}>
							<Table
								className={Styles.pageList}
								rowKey={record => record.id}
								dataSource={this.props.list}
								pagination={pageConfig}
								columns={columns}
							/>
						</Col>
					</Row>
				</Form>
				<MaterialModal
					onHide={this.hide}
					visible={this.state.visible}
					materialList={this.props.materialList}
				/>
			</div>
		)
	}
}

export default connect((state) => {
	const { list, totalCount, materialList } = state.packetList;
	const { permissions } = state.indexPage;
	return {
		list,
		totalCount,
		materialList,
		permissions
	}
})(createForm({})(SearchList))
